package com.hnair.grpc.example.utils;

import io.grpc.Attributes;
import io.grpc.Context;
import io.grpc.ServerCall;

import javax.security.auth.Subject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GrpcUtil {


    private GrpcUtil() {

    }

    /* 客户端 ID */
    public static final String CLIENT_ID = "client_id";

    /* 客户端真实 IP */
    public static final String X_FORWARDED_FOR = "x-forwarded-for";

    /* 客户端 IP */
    public static final String CLIENT_IP = "remote-addr";

    /* 客户端 IP */
    public static final String NON = "NON";

    /* 终端用户 IP */
    public static final String REMOTE_IP = "remoteip";

    /* 是否关闭请求 */
    public static final String IS_CLOSE = "IS_CLOSE";

    /* 令牌 */
    public static final String TOKEN = "token";

    /* 客户端 IP 格式 */
    public static final String CLIENT_IP_REG = "\\/?(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}):\\d{1,5}";

    /* IP 格式 */
    public static final String IP_REG = "\\/?(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3})";

    /* 服务名格式 */
    public static final String SERVICE_REG = "(.*)\\.([0-9A-Za-z_]+)\\/([0-9A-Za-z_]+)";

    /**
     * 获取客户端 IP
     *
     * @return
     */
    public static <ReqT, RespT> String getClientIP(ServerCall<ReqT, RespT> serverCall) {
        String clientIP = "";
        for (Attributes.Key<?> key : serverCall.getAttributes().keys()) {
            if (CLIENT_IP.equals(key.toString())) {
                String remoteAddr = serverCall.getAttributes().get(key).toString();
                Matcher matcher = Pattern.compile(GrpcUtil.CLIENT_IP_REG).matcher(remoteAddr);
                if (matcher.find()) {
                    clientIP = matcher.group(1);
                }
                break;
            }
        }
        return clientIP;
    }

    public static boolean isIP(String remoteAddr) {
        Matcher matcher = Pattern.compile(GrpcUtil.IP_REG).matcher(remoteAddr);
        return matcher.find();
    }
}
